<template>
  <div>
    <StepTabs :tabs="tabsList" v-model="activeIndex"></StepTabs>
    <div class="from-content" v-if="activeIndex == 1">
      <AplidForm ref="formRef" v-bind="projectConfig" v-model="formModel" @submit="onSubmit"></AplidForm>
      <div class="footer-btn fc">
        <el-button @click="formRef.onSubmit()" type="primary">下一步</el-button>
      </div>
    </div>

    <template v-if="activeIndex == 2">
      <div class="config-content">
        <policyArchive :list="nowData.policyRel"></policyArchive>
      </div>
      <div class="footer-btn">
        <div class="block">
          <span class="label">申请日期</span>
          <el-date-picker v-model="formModel.belongDate" type="month" value-format="YYYY-MM-DD" placeholder="请选择日期" />
        </div>
        <div class="w-100 fc">
          <el-button @click="handleProd">上一步</el-button>
          <el-button type="primary" @click="handleNext">下一步</el-button>
        </div>
      </div>
    </template>

    <template v-if="activeIndex == 3">
      <ApplyReport :nowRowData="{ ...nowData, ...formModel }" @refresh-change="onRefreshChange"></ApplyReport>
      <div class="footer-btn">
        <div class="w-100 fc">
          <el-button @click="handleProd">上一步</el-button>
          <el-button type="primary" @click="handleSubmitApply">确认</el-button>
        </div>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import apiMod from '@/apiMod/index'
import remoteSelect from '@/components/AplidCrud/src/AplidRemote/index'
import StepTabs from '@/views/instOperate/components/StepTabs/index.vue'
import policyArchive from '@/views/instOperate/components/policyArchive/index.vue'
import ApplyReport from './ApplyReport/index.vue'
import { formProjectConfig } from '../config'
import { getStore } from '@/utils/store'
import { md5 } from '@/utils/encdecrpt'

const props = withDefaults(
  defineProps<{
    subsidyType?: string | number
    bedApplyType?: string | number
    applySource?: number
  }>(),
  {}
)
const emit = defineEmits(['refresh'])
const formModel: any = ref({
  bedApplyType: props.bedApplyType || 1, // 床位申请类型
  belongDate: '',
  subsidyType: props.subsidyType,
})
const projectConfig = computed(() => {
  return formProjectConfig(props.subsidyType, props.applySource)
})
const pageReload: any = inject('reload')

const userInfo = getStore('userInfo') || {}
const orgInfo = getStore('organizationInfo') || {}
const formRef = ref(null)
const activeIndex = ref(1)

const tabsList = [
  { label: '01.选择补贴项目', value: 1, tip: '选择对应的补贴项目' },
  { label: '02.申请须知', value: 2, tip: '关于申请养老机构综合运营补贴的政策文件' },
  { label: '03.提交材料', value: 3, tip: '根据政策文件，提供相关文件' },
]

const nowData: any = ref({})

const handleNext = () => {
  if (!formModel.value.belongDate) {
    ElMessage.warning('请选择申请日期')
    return
  }
  nowData.value.belongDate = formModel.value.belongDate

  const getYearMonth = (belongDate) => {
    const year = belongDate.replace('年', '-').replace('月', '').split('-')[0]
    const month = belongDate.replace('年', '-').replace('月', '').split('-')[1]
    return { year, month }
  }
  apiMod
    .view_subsidy_getData({
      projectId: formModel.value.subsidyProjectId,
      creditCode: userInfo.organizationId,
      ...getYearMonth(formModel.value.belongDate),
    })
    .then((res) => {
      if (res.data == 0) {
        onNext()
      } else {
        ElMessage.warning('该项目已存在申请，请勿重复申请！')
      }
    })
}

const onNext = () => {
  if (activeIndex.value < tabsList.length) {
    activeIndex.value += 1
  }
}

const handleProd = () => {
  if (activeIndex.value > 1 && activeIndex.value <= tabsList.length) {
    activeIndex.value -= 1
  }
}
const onSubmit = (form, done) => {
  const submit = () => {
    apiMod.view_ofsSubsidyApplyConfig_view(form.subsidyApplyConfigId).then((res) => {
      nowData.value = {
        ...(res.data || {}),
      }
      onNext()
    })
  }
  // 机构运营补贴添加安全检测提示
  if (form.subsidyType == 2) {
    ElMessageBox.confirm('一年内未发生消防安全、食物中毒及其他安全责任事故', '确认提醒', {
      showClose: false,
      confirmButtonText: '确定',
      cancelButtonText: '放弃补贴',
      distinguishCancelAndClose: true,
      closeOnClickModal: false,
      type: 'warning',
    })
      .then(() => {
        // 获取项目配置
        submit()
      })
      .catch(() => {
        pageReload()
      })
    return false
  }
  // 获取项目配置
  submit()
  done()
}

const onRefreshChange = (formId, tabsList) => {
  const tableJson = tabsList ? JSON.parse(tabsList) : []
  // 判断有没有床位第二笔申请表
  const tempJson_1004 = tableJson.find((item) => item.value == 'bed_report_1004')
  const tempJson_1011 = tableJson.find((item) => item.value == 'bed_report_1011')
  const tempJson_hl_1001 = tableJson.find((item) => item.value == 'bed_hl_report_1001')
  const tempJson_hl_1006 = tableJson.find((item) => item.value == 'bed_report_1006')
  const tempJson_pk_hl_1001 = tableJson.find((item) => item.value == 'PK_bed_hl_report_1001')
  const tempJson_pk_1004 = tableJson.find((item) => item.value == 'PK_bed_report_1004')
  if (tempJson_1004 || tempJson_1011 || tempJson_pk_1004) {
    formModel.value.bedApplyType = 2
  }
  if (tempJson_hl_1001 || tempJson_hl_1006 || tempJson_pk_hl_1001) {
    formModel.value.bedApplyType = 3
  }

  formModel.value.applyNo = formId
}

const handleSubmitApply = () => {
  const params: any = {
    belongDate: formModel.value.belongDate,
    creditCode: userInfo.organizationId,
    subsidyProjectId: formModel.value.subsidyProjectId,
    applyNo: formModel.value.applyNo,
    bedApplyType: formModel.value.bedApplyType,
  }
  if (!formModel.value.applyNo) {
    const str = [params?.creditCode, params?.belongDate?.replace('-', '').substring(0, 6), params?.subsidyProjectId].filter(Boolean).join('_')
    params.applyNo = md5(str)
  }
  if (props.subsidyType == 1) {
    params.applyType = 5
    params.firstId = formModel.value.firstId
  }

  apiMod.view_ofsSubsidyApply_add(params).then(() => {
    ElMessage.success('提交成功')
    if (props.subsidyType == 1) {
      // 新增勘察记录 床位补贴类型
      apiMod
        .view_ofsSubsidyApplySurvey_add({
          orgName: orgInfo.organizationName,
          creditCode: orgInfo.creditCode,
          orgAddress: orgInfo.organizationAddress,
          applyNo: params.applyNo,
          burdenUserName: orgInfo.burdenUserName,
          burdenUserPhone: orgInfo.burdenUserPhone,
        })
        .then(() => {
          emit('refresh')
        })
        .catch(() => {
          emit('refresh')
        })
    } else {
      emit('refresh')
    }
  })
}

watch(
  () => formModel.value.subsidyType,
  () => {
    formModel.value.subsidyProjectName = undefined
    formModel.value.subsidyApplyConfigId = undefined
  },
  {
    immediate: true,
  }
)
</script>

<style scoped lang="scss">
.from-content {
  width: 50%;
  margin: 100px auto;
}

.config-content {
  padding: 12px;
  margin-top: 20px;
  border: 1px solid #dcdcdc;
  border-radius: 10px;
}

.footer-btn {
  margin-top: 32px;

  .block {
    display: flex;
    align-items: center;

    .label {
      margin-right: 12px;
    }
  }
}
</style>
